package com.example.agricultural_big_data.service.serviceimpl;

import com.example.agricultural_big_data.mapper.EmailMapper;
import com.example.agricultural_big_data.pojo.Result;
import com.example.agricultural_big_data.pojo.ResultCode;
import com.example.agricultural_big_data.service.EmailService;
import com.example.agricultural_big_data.util.MD5Util;
import com.example.agricultural_big_data.util.RandomNumUtil;
import com.example.agricultural_big_data.util.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * @author xiao yang
 * @Description: 邮箱
 * @date 2021/3/913:59
 */
@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    JavaMailSender mailSender;//注入QQ发送邮件的bean
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    Result result;

    @Autowired
    EmailMapper emailMapper;
    @Override
    public JSONObject sendEmail(JSONObject data){
        String email = data.getString("email");
        RandomNumUtil randomNumUtil=new RandomNumUtil();
        String randomNum= randomNumUtil.getRandNum();
        redisUtil.set(randomNum,randomNum,300);
        try {
            MimeMessage mimeMessage = this.mailSender.createMimeMessage();
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setFrom("2945834875@qq.com");//设置发件qq邮箱
            message.setTo(email);            //设置收件人
            message.setSubject("验证码");    //设置标题
            message.setText("你的验证码是: " +randomNum, true);
            this.mailSender.send(mimeMessage);
            return result.responseResult(ResultCode.success.getStatusCode(),ResultCode.success.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return result.responseResult(ResultCode.fail.getStatusCode(),ResultCode.fail.getMsg());
        }
    }

    @Override
    public JSONObject verifyCode(JSONObject data) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String code=data.getString("code");
        String dbcode=(String)redisUtil.get(code);
        String passwd=data.getString("password");
        String dbpass= MD5Util.getEncryptedPwd(passwd);
        String name=data.getString("name");
        if (dbcode!=null){
            emailMapper.updatePass(name,dbpass);
            return result.responseResult(ResultCode.success.getStatusCode(),ResultCode.success.getMsg());
        }else {
            return result.responseResult(ResultCode.no_match.getStatusCode(),ResultCode.no_match.getMsg());
        }
    }


}
